const request = require("../../utils/request.js").request;

const router = require("../../utils/router.js").router;


Page({

  data: {
    invoice: {
      invoiceId:"",
      accountBank: "",
      amount: 0,
      date: "",
      // items: [],
    },

    items:[],
    itemNumber:0,
    startTime: "2019-02-03",
    endTime: "2021-01-01",
    date: "2021-01-01",
    choosenFiles: [],
    maxFileNum: 1,
    currentFileNum: 0,
  },

  onShow: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDay() + 1;

    var strMonth = parseInt(month) < 10 ? "0" + month : month;

    var strDay = parseInt(day) < 10 ? "0" + day : day;

    this.setData({
      date: year + '-' + strMonth + '-'  + strDay,
      endTime: year + '-' + strMonth + '-'  + strDay,
      startTime: "1987-01-01",
    })
  },

  refresh: function() {

    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDay() + 1;

    var strMonth = parseInt(month) < 10 ? "0" + month : month;

    var strDay = parseInt(day) < 10 ? "0" + day : day;

    this.setData({
      invoice: {
        invoiceId:"",
        accountBank: "",
        amount: 0,
        date: year + '-' + strMonth + '-'  + strDay,
        // items: [],
      },
  
      items:[],
      itemNumber:0,
      date: "2021-01-01",
      choosenFiles: [],
      currentFileNum: 0,
    })
  },

  pickerChange: function(e) {
    let invoice = this.data.invoice;
    invoice.date = e.detail.value;
    this.setData({
      date: e.detail.value,
      invoice: invoice,
    })
  },

  addEmptyItem: function() {
    var itemNumber = this.data.itemNumber;
    let items = this.data.items;
    items[itemNumber] = {
      name: '',
      amount: '',
    }
    itemNumber++;
    this.setData({
      itemNumber: itemNumber,
      items: items,
    });
  },

  invoiceIdInput(e) {
    let invoice = this.data.invoice;
    invoice.invoiceId = e.detail.value;
    this.setData({
      invoice: invoice,
    })
  },

  accountBankInput: function(e) {
    let invoice = this.data.invoice;
    invoice.accountBank = e.detail.value;
    this.setData({
      invoice: invoice,
    })
  },

  amountInput: function(e) {
    let invoice = this.data.invoice;
    invoice.amount = e.detail.value;
    this.setData({
      invoice: invoice,
    })
  },

  itemNameInput: function(e) {
    let index = e.target.dataset.index;
    let itemName = e.detail.value;
    let items = this.data.items;
    if (items[index] == undefined) {
      items[index] = new Object();
    }
    items[index].name = itemName;
    this.setData({
      items: items,
    })
  },

  itemAmountInput: function(e) {
    let index = e.target.dataset.index;
    let amount = e.detail.value;
    let items = this.data.items;
    if (items[index] == undefined) {
      items[index] = new Object();
    }
    items[index].amount = amount;
    this.setData({
      items: items,
    })
  },

  delItem: function(e) {

    let index = e.target.dataset.index;
    let items = this.data.items;

    items.splice(index, 1);

    let itemNumber = this.data.itemNumber;

    if (itemNumber > 0) {
      itemNumber--;
    }

    this.setData({
      items: items,
      itemNumber: itemNumber,
    })
  },


  chooseFile: function(e) {
    var that = this;
    const maxFileNum = this.data.maxFileNum;
    var currentFileNum = this.data.currentFileNum;

    if (currentFileNum < maxFileNum) {
      wx.chooseMessageFile({
        type: "all",
        count: maxFileNum,
      }).then(function(res) {
        var choices = res.tempFiles;
        var choosenFiles = that.data.choosenFiles;
        choosenFiles = choosenFiles.concat(choices);

        currentFileNum += choices.length;
        that.setData({
          choosenFiles: choosenFiles,
          currentFileNum: currentFileNum,
        })
      }).catch(function(errMsg) {
        // Ignore cancel
      })
    }
  },

  handleSubmit() {

    if (!this.checkParams()) {
      return;
    }

    wx.showToast({
      title: '信息上传中',
      icon: "loading",
    })

    var that = this;

    const userModal = wx.getStorageSync('user');
    if (userModal == null || userModal === undefined || userModal.trim() == '') {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }

    var uploadFile = this.data.choosenFiles[0];
    let filePath = uploadFile.path;
    let fileName = uploadFile.name;
    

    let invoice = this.data.invoice;
    let invoiceItems = this.data.items;
    let invoiceItemsStr = JSON.stringify(invoiceItems);
    let date = this.data.date;

    // invoice.items = invoiceItems;
    wx.uploadFile({
      filePath: filePath,
      name: "files",
      url: router.host + router.uploadInvoice,
      formData: {
        userModal: userModal,
        accountBank: invoice.accountBank,
        invoiceId: invoice.invoiceId,
        amount: invoice.amount,
        date: date,
        invoiceItems: invoiceItemsStr,
      },
      success: function(res) {

        let resData = JSON.parse(res.data);

        if (resData.code == 502) {
          wx.navigateTo({
            url: '../login/login',
          })
        } else if (resData.code == 200) {
          wx.showToast({
            title: '上传成功！',
            icon: "success",
          })
          that.refresh();
        } else if (resData.code == 503) {
          wx.showToast({
            title: '发票编号冲突！',
            icon:"none",
          })
          return;
        }
      },
      fail: function(errMsg) {
      }
    })
  },

  checkParams() {
    const invoice = this.data.invoice;
    const items = this.data.items;
    const choosenFiles = this.data.choosenFiles;

    if (invoice.invoiceId == null || invoice.invoiceId === undefined || invoice.invoiceId.trim() === '') {
      wx.showToast({
        title: '请输入发票编号！',
        icon: "none",
      })
      return false;
    }

    if (invoice.accountBank == null || invoice.accountBank === undefined || invoice.accountBank.trim() === '') {
      wx.showToast({
        title: '请输入开户行！',
        icon: "none",
      })
      return false;
    }

    if (invoice.amount == null || invoice.amount === undefined || invoice.amount === 0) {
      wx.showToast({
        title: '请输入报销金额！',
        icon: "none",
      })
      return false;
    }

    if (items == null || items == undefined || items.length === 0) {
      wx.showToast({
        title: '请至少填写一个报销物品！',
        icon: "none",
      })
      return false;
    }

    if (choosenFiles == null || choosenFiles == undefined || choosenFiles.length === 0) {
      wx.showToast({
        title: '请上传文件！',
        icon: "none",
      })
      return false;
    }
    return true;
  }
})